#include "music_player.h"
#include <QTime>
#include <QDebug>
#include <QVBoxLayout>
#include <QFormLayout>
#include <QLineEdit>
#include <QTextEdit>
#include <QDialogButtonBox>
#include <QIcon>
#include <QRegExp>
#include <QNetworkRequest>
#include <QJsonParseError>
#include <QMediaPlayer>

music_player::music_player(QWidget *parent) : QWidget(parent),
    currentIndex(-1), isPlaying(false)
{
    player = new QMediaPlayer(this);
    playlist = new QMediaPlaylist(this);
    player->setPlaylist(playlist);
    
    // 初始化网络和定时器
    networkManager = new QNetworkAccessManager(this);
    lyricTimer = new QTimer(this);
        
    // 初始化界面和连接  
    initUI();
    initConnections();
    createPopupDialog();
            
            // 添加示例音乐，包含歌手信息和图片
            addMusic("可惜没如果(Live)", "林俊杰", "歌词", 
                     "http://music.163.com/song/media/outer/url?id=399354373.mp3", ":/images/singer1.jpg","399354373");
            addMusic("红蔷薇白玫瑰 (G.E.M.重生版)", "G.E.M.邓紫棋", "歌词", 
                     "http://music.163.com/song/media/outer/url?id=2714278533.mp3", ":/images/singer1.jpg","2714278533");
            addMusic("人间不值得", "黄诗扶", "歌词", 
                     "http://music.163.com/song/media/outer/url?id=1340543218.mp3", ":/images/singer1.jpg","1340543218");
        
        // 默认播放第一首
            playlist->setPlaybackMode(QMediaPlaylist::Loop); // 设置循环播放
               if (!musicList.isEmpty()) {
                   setCurrentMusicIndex(0);
               }
}

music_player::~music_player()
{
    delete popupDialog;
    // Qt父对象会处理子控件的销毁
    delete playlist;
}

void music_player::initUI()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(10, 10, 10, 10);
    mainLayout->setSpacing(10);
    
    // 顶部布局（包含弹窗按钮）
    QHBoxLayout *topLayout = new QHBoxLayout();
    
    // 左上角弹窗按钮
    popupBtn = new QPushButton(this);
    popupBtn->setIcon(QIcon(":/音乐小狗"));
    popupBtn->setIconSize(QSize(24, 24));
    popupBtn->setStyleSheet("QPushButton { border: none; background: transparent; }"
                          "QPushButton:hover { background: rgba(0, 0, 0, 0.05); border-radius: 4px; }");
    topLayout->addWidget(popupBtn);
    topLayout->addStretch();
    
    mainLayout->addLayout(topLayout);
    
    // 歌曲信息布局（歌手图片 + 标题 + 歌手名）
    QHBoxLayout *infoLayout = new QHBoxLayout();
    infoLayout->setSpacing(12);
    
    // 歌手图片
    singerImageView = new QLabel(this);
    singerImageView->setFixedSize(32,32);
    singerImageView->setStyleSheet("border-radius: 5px; background-color: #eee;");
    singerImageView->setScaledContents(true);
    singerImageView->setAlignment(Qt::AlignCenter);
    singerImageView->setMinimumSize(32,32); // 确保尺寸固定
    infoLayout->addWidget(singerImageView);
    
    // 文本信息布局（确保歌名和歌手名左对齐且垂直居中） // 标题和歌手名布局
        QVBoxLayout *textInfoLayout = new QVBoxLayout();
        textInfoLayout->setSpacing(4); // 歌名与歌手名的垂直间距
        textInfoLayout->setContentsMargins(0, 0, 0, 0);
        textInfoLayout->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); // 左对齐且垂直居中
    
    
    // 标题标签
    titleLabel = new QLabel(this);
    titleLabel->setStyleSheet("font-size: 16px; font-weight: bold; color: #333; background: transparent;");
    
    // 歌手标签
    singerLabel = new QLabel(this);
    singerLabel->setStyleSheet("font-size: 12px; color: #666; background: transparent;");
    
    textInfoLayout->addWidget(titleLabel);
    textInfoLayout->addWidget(singerLabel);
    textInfoLayout->addStretch();
    
    infoLayout->addLayout(textInfoLayout);
    infoLayout->addStretch();
    
    mainLayout->addLayout(infoLayout);
    
    // 歌词标签
    lyricLabel = new QLabel(this);
    lyricLabel->setStyleSheet("font-size: 12px; color: #666; padding: 4px; background: transparent;");
    lyricLabel->setAlignment(Qt::AlignCenter);
    lyricLabel->setWordWrap(true);
    mainLayout->addWidget(lyricLabel);
    
    // 进度条和时间条容器（放在一个框内）
    progressContainer = new QWidget(this);
    progressContainer->setStyleSheet("background-color: rgba(210,237,255,1.00); border-radius: 5px;");
    QVBoxLayout *progressLayout = new QVBoxLayout(progressContainer);
    progressLayout->setContentsMargins(5, 5, 5, 5);
    progressLayout->setSpacing(5); // 缩小进度条和时间条的距离
    
    // 进度条
    progressSlider = new QSlider(Qt::Horizontal, this);
    progressSlider->setStyleSheet("QSlider::groove:horizontal { height: 4px; background: #ddd; border-radius: 2px; }"
                                 "QSlider::handle:horizontal { width: 12px; height: 12px; margin: -4px 0; background: #4285F4; border-radius: 6px; }");
    progressLayout->addWidget(progressSlider);
    
    // 时间显示
    timeLabel = new QLabel("00:00                            00:00", this);
    timeLabel->setStyleSheet("font-size: 9px; color: #666;");
    timeLabel->setAlignment(Qt::AlignRight);
    progressLayout->addWidget(timeLabel);
    
    mainLayout->addWidget(progressContainer);
    
    // 控制按钮布局
    QHBoxLayout *controlLayout = new QHBoxLayout();
    
    // 上一曲按钮
    prevBtn = new QPushButton(this);
    prevBtn->setIcon(QIcon(":/上一首"));
    prevBtn->setIconSize(QSize(32, 32));
    prevBtn->setStyleSheet("QPushButton { border: none; background: transparent; }"
                         "QPushButton:hover { background: rgba(0, 0, 0, 0.05); border-radius: 4px; }");
    
    // 播放/暂停按钮
    playPauseBtn = new QPushButton(this);
    playPauseBtn->setIcon(QIcon(":/播放"));
    playPauseBtn->setIconSize(QSize(32, 32));
    playPauseBtn->setStyleSheet("QPushButton { border: none; background: transparent; }"
                              "QPushButton:hover { background: rgba(0, 0, 0, 0.05); border-radius: 4px; }");
    
    // 下一曲按钮
    nextBtn = new QPushButton(this);
    nextBtn->setIcon(QIcon(":/下一首"));
    nextBtn->setIconSize(QSize(32, 32));
    nextBtn->setStyleSheet("QPushButton { border: none; background: transparent; }"
                         "QPushButton:hover { background: rgba(0, 0, 0, 0.05); border-radius: 4px; }");
    
    // 添加按钮到布局
    controlLayout->addStretch();
    controlLayout->addWidget(prevBtn);
    controlLayout->addSpacing(15);
    controlLayout->addWidget(playPauseBtn);
    controlLayout->addSpacing(15);
    controlLayout->addWidget(nextBtn);
    controlLayout->addStretch();
    
    mainLayout->addLayout(controlLayout);
    
    setLayout(mainLayout);
    
    // 设置播放器背景
    setStyleSheet("background-color: #f5f5f5; border-radius: 8px;");
}

void music_player::initConnections()
{
    // 连接按钮信号
    connect(prevBtn, &QPushButton::clicked, this, &music_player::prev);
    connect(playPauseBtn, &QPushButton::clicked, this, &music_player::playPause);
    connect(nextBtn, &QPushButton::clicked, this, &music_player::next);
    connect(popupBtn, &QPushButton::clicked, this, &music_player::onPopupButtonClicked);
    
    // 连接进度条信号
    connect(progressSlider, &QSlider::sliderMoved, this, &music_player::setPosition);
    
    // 连接播放器信号
    connect(player, &QMediaPlayer::positionChanged, this, &music_player::updatePosition);
    connect(player, &QMediaPlayer::durationChanged, this, &music_player::updateDuration);
    connect(player, &QMediaPlayer::stateChanged, [this](QMediaPlayer::State state) {
        isPlaying = (state == QMediaPlayer::PlayingState);
        playPauseBtn->setIcon(isPlaying ? QIcon(":/暂停") : QIcon(":/播放"));
    });
    connect(player, &QMediaPlayer::mediaStatusChanged, [this](QMediaPlayer::MediaStatus status) {
        if (status == QMediaPlayer::EndOfMedia) {
            next();
        }
    });
    // 歌词定时器连接
        connect(lyricTimer, &QTimer::timeout, this, &music_player::updateLyricDisplay);
    
        // 播放器错误处理
        connect(player, QOverload<QMediaPlayer::Error>::of(&QMediaPlayer::error),
                [this](QMediaPlayer::Error error) {
            qDebug() << "播放错误:" << player->errorString();
        });
}

void music_player::addMusic(const QString &title, const QString &singer, const QString &lyric, 
                          const QString &filePath, const QString &singerImagePath, const QString &songId)
{
    MusicInfo info;
    info.title = title;
    info.singer = singer;
    info.lyric = lyric;
    info.filePath = filePath;
    info.singerImagePath = singerImagePath;
    info.songId= songId;  // 存储歌曲ID
    musicList.append(info);
    
    // 如果是第一首音乐，设置为当前播放
    playlist->addMedia(QUrl::fromLocalFile(filePath));
   
       if (musicList.size() == 1) {
           setCurrentMusicIndex(0);
       }
}

void music_player::setCurrentMusicIndex(int index)
{
    if (index >= 0 && index < musicList.size()) {
        currentIndex = index;
        updateMusicInfo();
        playlist->setCurrentIndex(index);
        
        // 请求当前歌曲的歌词
                QString songId = musicList[index].songId;
                if (!songId.isEmpty()) {
                    fetchLyric(songId);
                }
    }
}

void music_player::playPause()
{
    if (musicList.isEmpty()) return;
    
    if (isPlaying) {
        player->pause();
         lyricTimer->stop(); // 补充事项4：暂停时停止定时器
    } else {
        player->play();
         lyricTimer->start(100); // 补充事项4：播放时启动定时器（100ms间隔）
    }
}

void music_player::prev()
{
    if (musicList.isEmpty()) return;
    
    currentIndex = (currentIndex - 1 + musicList.size()) % musicList.size();
    setCurrentMusicIndex(currentIndex);
    player->play();
}

void music_player::next()
{
    if (musicList.isEmpty()) return;
    
    currentIndex = (currentIndex + 1) % musicList.size();
    setCurrentMusicIndex(currentIndex);
    player->play();
}

void music_player::updatePosition(qint64 position)
{
    progressSlider->blockSignals(true);
    progressSlider->setValue(position);
    progressSlider->blockSignals(false);
    
    // 更新时间显示
    QTime currentTime(0, position / 60000, qint64((position % 60000) / 1000));
    QTime totalTime(0, player->duration() / 60000, qint64((player->duration() % 60000) / 1000));
    timeLabel->setText(currentTime.toString("mm:ss") + " / " + totalTime.toString("mm:ss"));
}

void music_player::setPosition(int position)
{
    player->setPosition(position);
}

void music_player::updateDuration(qint64 duration)
{
    progressSlider->setRange(0, duration);
}

void music_player::updateMusicInfo()
{
    if (currentIndex >= 0 && currentIndex < musicList.size()) {
            titleLabel->setText(musicList[currentIndex].title);
            singerLabel->setText(musicList[currentIndex].singer);
            
            // 显示默认文本直到歌词加载完成
            if (lyricLines.isEmpty()) {
                lyricLabel->setText("加载歌词中...");
            }
        // 设置歌手图片
        if (!musicList[currentIndex].singerImagePath.isEmpty()) {
            QPixmap singerPixmap(musicList[currentIndex].singerImagePath);
            if (!singerPixmap.isNull()) {
                    singerImageView->setPixmap(singerPixmap.scaled(60,60, 
                          Qt::KeepAspectRatio, Qt::SmoothTransformation));
                return;
            }
        }
        // 如果没有歌手图片，显示默认图标
        singerImageView->setPixmap(QPixmap(":/音乐播放"));
    }
}

void music_player::createPopupDialog()
{
    // 创建弹窗
    popupDialog = new QDialog(this);
    popupDialog->setWindowTitle("信号音乐中心");
    popupDialog->resize(300, 400);
    
    QVBoxLayout *dialogLayout = new QVBoxLayout(popupDialog);
    
    // 弹窗内容 - 可以根据需要自定义
    QLabel *dialogLabel = new QLabel("歌曲详细信息", popupDialog);
    dialogLabel->setAlignment(Qt::AlignCenter);
    dialogLabel->setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px;");
    
    QFormLayout *formLayout = new QFormLayout();
    QLineEdit *titleEdit = new QLineEdit();
    QLineEdit *singerEdit = new QLineEdit();
    QTextEdit *lyricEdit = new QTextEdit();
    lyricEdit->setMinimumHeight(80);
    
    formLayout->addRow("歌名:", titleEdit);
    formLayout->addRow("歌手:", singerEdit);
    formLayout->addRow("歌词:", lyricEdit);
    
    // 按钮盒
    QDialogButtonBox *buttonBox = new QDialogButtonBox(
        QDialogButtonBox::Ok | QDialogButtonBox::Cancel, 
        Qt::Horizontal, popupDialog);
    
    connect(buttonBox, &QDialogButtonBox::accepted, popupDialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, popupDialog, &QDialog::reject);
    
    dialogLayout->addWidget(dialogLabel);
    dialogLayout->addLayout(formLayout);
    dialogLayout->addWidget(buttonBox);
    
    popupDialog->setLayout(dialogLayout);
}

void music_player::onPopupButtonClicked()
{
    if (popupDialog && currentIndex >= 0 && currentIndex < musicList.size()) {
        // 在弹窗中显示当前歌曲信息
        QLineEdit *titleEdit = popupDialog->findChild<QLineEdit*>();
        if (titleEdit) titleEdit->setText(musicList[currentIndex].title);
        
        QLineEdit *singerEdit = popupDialog->findChild<QLineEdit*>();
        if (singerEdit) singerEdit->setText(musicList[currentIndex].singer);
        
        QTextEdit *lyricEdit = popupDialog->findChild<QTextEdit*>();
        if (lyricEdit) lyricEdit->setText(musicList[currentIndex].lyric);
        
        popupDialog->exec();
    }
}

void music_player::fetchLyric(const QString &songId)
{
    // 清空现有歌词
        lyricLines.clear();
        currentLyricIndex = -1;
        
        // 网易云音乐歌词API（需替换为有效接口）
        QString url = QString("http://music.163.com/api/song/lyric?id=%1&lv=1&kv=1&tv=-1").arg(songId);
        QNetworkRequest request(url); // 这样构造出 QNetworkRequest 对象，再传给 get 方法
        
        // 发送网络请求
        QNetworkReply *reply = networkManager->get(request);
        connect(reply, &QNetworkReply::finished, this, [this, reply]() {
            onLyricReplyFinished(reply);
    });
}

void music_player::onLyricReplyFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
            qDebug() << "歌词请求错误:" << reply->errorString();
            reply->deleteLater();
            return;
        }
    
        // 读取响应数据
        QByteArray data = reply->readAll();
        reply->deleteLater();
    
        // 解析JSON（假设返回格式为 {"lrc":{"lyric":"歌词内容"}}）
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(data, &error);
        if (error.error != QJsonParseError::NoError) {
            qDebug() << "歌词JSON解析错误:" << error.errorString();
            return;
        }
    
        QJsonObject root = doc.object();
        QJsonObject lrcObj = root["lrc"].toObject();
        QString lyricText = lrcObj["lyric"].toString();
    
        // 解析歌词文本
        parseLyricText(lyricText);
        
        // 启动歌词定时器（每100ms更新一次）
        lyricTimer->start(100);
}

void music_player::parseLyricText(const QString &lyricText)
{
    // 正则表达式匹配 [mm:ss.ms] 格式的时间戳
       QRegExp reg("\\[(\\d+):(\\d+).(\\d+)\\](.*)");
       QStringList lines = lyricText.split("\n");
   
       foreach (const QString &line, lines) {
           if (reg.indexIn(line) != -1) {
               // 提取时间戳（转换为毫秒）
               int minute = reg.cap(1).toInt();
               int second = reg.cap(2).toInt();
               int msec = reg.cap(3).toInt() * 10; // 通常是0-99，转换为0-990ms
               qint64 time = minute * 60000 + second * 1000 + msec;
   
               // 提取歌词内容
               QString text = reg.cap(4).trimmed();
               if (!text.isEmpty()) {
                   lyricLines.append(qMakePair(time, text));
               }
           }
       }
   
       // 按时间戳排序
       std::sort(lyricLines.begin(), lyricLines.end(),
                 [](const QPair<qint64, QString> &a, const QPair<qint64, QString> &b) {
                     return a.first < b.first;
                 });
}

void music_player::updateLyricDisplay()
{
    if (lyricLines.isEmpty() || player->state() != QMediaPlayer::PlayingState) {
            return;
        }
    
        qint64 currentPos = player->position();
        int newIndex = -1;
    
        // 查找当前时间对应的歌词索引
        for (int i = 0; i < lyricLines.size(); ++i) {
            if (lyricLines[i].first <= currentPos) {
                newIndex = i;
            } else {
                break;
            }
        }
    
        // 更新显示（只在索引变化时更新）
        if (newIndex != -1 && newIndex != currentLyricIndex) {
            currentLyricIndex = newIndex;
            lyricLabel->setText(lyricLines[currentLyricIndex].second);
        }
}
